﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;

namespace GameForKids
{
    class FindCharactersGamePlay : DrawableGameComponent
    {
        // bien dem thoi gian
        public float milisecon = 0;
        // hien thi thoi gian choi
        public string timePlay = "";
        public int moved = 0;

        private SpriteFont helpFont;

        // Game Object
        public List<Couple> Couples;

        public SoundEffect soundClick;
        public SoundEffect soundCorrect;

        public int CountClick;
        public int CountClickTrue;
        public int CountReclickPlaySound;
        int count = 9;

        // cong thuc tinh diem
        public static string CongThucGoc = "100/N-T/20";
        public static string CongThucHienTai = "";

        public void Reset(int _level)
        {
            Couples = new List<Couple>();
            List<Vector2> positions = new List<Vector2>();
            List<int> indexs = new List<int>();
            List<int> temp = new List<int>();
            
            for (int i = 0; i <= 53; i++)
            {
                temp.Add(i);
            }

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 6; j++)
                {
                    positions.Add(new Vector2(i * 60 + 125, j * 70 + 70));
                }
            }
            count = 9;
            int start = 0;
            int end = 10;
            switch (_level)
            {
                case 1:
                    count = Suport.Random.Next(7, 9);
                    start = 0;
                    end = 9;
                    break;
                case 2:
                    count = Suport.Random.Next(12, 15);
                    start = 10;
                    end = 31;
                    break;
                case 3:
                    count = Suport.Random.Next(17, 20);
                    start = 10;
                    end = 53;
                    break;
                case 4:
                    count = Suport.Random.Next(23, 25);
                    start = 0;
                    end = 31;
                    break;
                case 5:
                    count = Suport.Random.Next(26, 28);
                    start = 0;
                    end = 53;
                    break;
                case 6:
                    count = Suport.Random.Next(29, 30);
                    start = 0;
                    end = 53;
                    break;
            }

            int dem = 0 ;

            while (indexs.Count < count)
            {
                dem++;
                int v = Suport.Random.Next(1, temp.Count + 1) - 1;
                if (start <= temp[v] && temp[v] <= end)
                {
                    if (indexs.Contains(temp[v]) == false)
                    {
                        if (temp[v] < 10)
                        {
                            indexs.Add(temp[v]);
                        }
                        else if (temp[v] >= 10 && temp[v] <= 31)
                        {
                            if (indexs.Contains(temp[v] + 22) == false)
                            {
                                indexs.Add(temp[v]);
                            }
                        }
                        else if (temp[v] > 31)
                        {
                            if (indexs.Contains(temp[v] - 22) == false)
                            {
                                indexs.Add(temp[v]);
                            }
                        }
                    }
                    temp.RemoveAt(v);
                }
            }

            for (int i = 1; i <= count; i++)
            {
 
                int v = Suport.Random.Next(1, indexs.Count + 1) - 1;
                int r = Suport.Random.Next(1, positions.Count + 1) - 1;

                int value = indexs[v];

                if (value >= 31)
                {
                    int valueTemp = value - 22;
                    if(GameForKids.language == GameForKids.VIET)
                        Couples.Add(new Couple("FindCharactersGame/Images/" + value, "FindCharactersGame/Sounds/VI/" + valueTemp, positions[r]));
                    else
                        Couples.Add(new Couple("FindCharactersGame/Images/" + value, "FindCharactersGame/Sounds/EN/" + valueTemp, positions[r]));
                }
                else
                {
                    if (GameForKids.language == GameForKids.VIET)
                        Couples.Add(new Couple("FindCharactersGame/Images/" + value, "FindCharactersGame/Sounds/VI/" + value, positions[r]));
                    else
                        Couples.Add(new Couple("FindCharactersGame/Images/" + value, "FindCharactersGame/Sounds/EN/" + value, positions[r]));
                }

                indexs.RemoveAt(v);
                positions.RemoveAt(r);
            }

            int index = Suport.Random.Next(1, Couples.Count + 1) - 1;
            Couples[index].IsWaitToCheck = true;
            Couples[index].OnRunTime = true;
            CountClick = 0;
            CountClickTrue = 0;
            CountReclickPlaySound = 0;
        }


        // tao co so du lieu
        private string strConnectionString = @"isostore:/FindCharactersGameDB.sdf";
        public FindCharactersGamePlay(Game game): base(game)
        {
            helpFont = this.Game.Content.Load<SpriteFont>("Fonts/HelpFont");
            soundClick = this.Game.Content.Load<SoundEffect>("FindSoundGame/Sounds/Click");
            soundCorrect = this.Game.Content.Load<SoundEffect>("FindSoundGame/Sounds/Correct");
            
            // tao csdl
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                if (readAndWriteDB.DatabaseExists() == false)
                {
                    readAndWriteDB.CreateDatabase();
                }
            }

            Reset(1);

            // lay cong thuc
            using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isolatedStorageFile.FileExists("CongThuc" + GameForKids.gameState.ToString() + ".txt"))
                {
                    using (IsolatedStorageFileStream isfs = isolatedStorageFile.OpenFile("CongThuc" + GameForKids.gameState.ToString() + ".txt", FileMode.Open))
                    {
                        using (StreamReader reader = new StreamReader(isfs))
                        {
                            while (!reader.EndOfStream)
                            {
                                CongThucHienTai = reader.ReadLine();
                            }
                        }
                    }
                }
            }
            if (CongThucHienTai == "" || CongThucHienTai == null)
                CongThucHienTai = CongThucGoc;
        }
     
        // luu theo dang ID - ten  - level - diem - ngay
        public void saveScore(int score)
        {
            string _name = GameForKids.userName;
            int _level = FindCharactersGame.level;
            int _score = score;
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                DataScore newscore = new DataScore { ID = DateTime.Now.ToString(),
                    name = _name, level = _level, score = _score, day = DateTime.Today.ToShortDateString() };
                readAndWriteDB.TableScore.InsertOnSubmit(newscore);
                readAndWriteDB.SubmitChanges();
            }
        }

        private IList<DataScore> getListDataScore(string _name, int _level)
        {
            IList<DataScore> listDataScore = null;
            using (ReadAndWrite readAndWrite = new ReadAndWrite(strConnectionString))
            {
                IQueryable<DataScore> dataScoreQuery = from data in readAndWrite.TableScore where data.name.Equals(_name) && data.level == _level select data;
                listDataScore = dataScoreQuery.ToList();
            }
            return listDataScore;
        }

        public void startNewLevel(int _level)
        {
            ChartScreen.listDataScore = this.getListDataScore(GameForKids.userName, _level);
            ChartScreen.levelOfGame = _level;
            milisecon = 0;
            moved = 0;
            Reset(_level);
        }

    

        //tinh diem
        public int getScore()
        {
            int mark = 0;
            XuLyCongThuc xulycongthuc;
            string s = "";

            xulycongthuc = new XuLyCongThuc();
            s = xulycongthuc.TinhDiem(CongThucHienTai, moved, (int)(milisecon / 1000), FindCharactersGame.level);
            double d = double.Parse(s);
            mark = (int)d;

            if (mark >= 10)
                return 10;
            if (mark <= 0)
                mark = 0;
            return mark;
        }

        public void doOnReplayClick()
        {
            foreach (Couple couple in Couples)
            {
                if (couple.IsWaitToCheck == true)
                {
                    if (couple.OnPlay == false)
                    {
                        Suport.GetSound(couple.SoundLink).Play();
                        couple.OnPlay = true;
                    }
                }
            }
        }

        // neu tat ca cac cell deu a^n thi Win
        public bool checkComplete()
        {
            if (Couples.Count == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public void setTimePlay()
        {
            timePlay = ((int)milisecon / 60000).ToString() + " : " + (((int)milisecon / 1000) % 60).ToString();
        }

        public override void Update(GameTime gameTime)
        {

            float elapsed = (float)gameTime.ElapsedGameTime.Milliseconds;
            milisecon += elapsed;
            setTimePlay();

            
        

            int index = -1;
            for (int i = 0; i < Couples.Count; i++ )
            {
                Couples[i].Update(gameTime);
                if (Couples[i].IsShow == false)
                {
                    index = i;
                }

                if (Couples[i].OnRunTime == true)
                {
                    if (Couples[i].TimeForPlay < 0.0f)
                    {
                        Couples[i].OnRunTime = false;
                        Couples[i].TimeForPlay = 2.0f;
                        Couples[i].IsWaitToCheck = true;

                            Suport.GetSound(Couples[i].SoundLink).Play();
                    }
                }
            }

            if (index != -1)
            {
                Couples.RemoveAt(index);
                if (Couples.Count != 0)
                {
                    Couples[Suport.Random.Next(1, Couples.Count + 1) - 1].OnRunTime = true;
                }
            }

            base.Update(gameTime);
        }

        public virtual void Draw(GameTime gametime, SpriteBatch spriteBatch)
        {
            foreach (Couple couple in Couples)
            {
                couple.Draw(spriteBatch);
            }
            spriteBatch.DrawString(helpFont, timePlay, new Vector2(10, 250), Color.White);
            spriteBatch.DrawString(helpFont, moved.ToString(), new Vector2(10, 300), Color.White);
        
        }

        public void TouchEvent(TouchLocation touch)
        {

                foreach (Couple couple in Couples)
                {
                    if (couple.CheckTouch(touch) == true)
                    {
                        if (couple.OnClick == false)
                        {
                            if (GameForKids.ISMUSIC)
                            {
                                soundClick.Play();
                            }
                            CountClick++;
                            moved++;
                            couple.OnClick = true;
                        }
                        if (couple.IsWaitToCheck == true)
                        {
                            if (couple.IsShow == true)
                            {
                                if (GameForKids.ISMUSIC)
                                {
                                    soundCorrect.Play();
                                }
                                CountClickTrue++;
                            }

                            couple.IsShow = false;
                        }
                        break;
                    }
                }
            
        }
    }
}
